<template>
	<view class="purchase-detail-container">
		<!-- 导航栏 -->
		<!-- <u-navbar title="进货单详情" :autoBack="true" bgColor="#ffffff"> -->
			<!-- 可以添加自定义操作，例如更多菜单 -->
		<!-- </u-navbar> -->

		<!-- 页面主要内容 -->
		<scroll-view scroll-y class="scroll-view-content">
			<view class="content-padding">
				<!-- 基础信息 -->
				<view class="info-section card">
					<view class="info-item">
						<text class="label">日期</text>
						<text class="value">{{ orderData.businessDate || 'N/A' }}</text>
					</view>
					<view class="info-item">
						<text class="label">供应商</text>
						<text class="value">{{ orderData.supplierName || 'N/A' }}</text>
					</view>
				</view>

				<!-- 商品信息 -->
				<view class="goods-section card">
					<view class="section-header">
						<text>选中货品 ({{ orderData.purchaseDetailItemList && orderData.purchaseDetailItemList.length || 0 }})</text>
						<text>合计金额: ¥{{ orderData.totalAmount && orderData.totalAmount.toFixed(2) || '0.00' }}</text>
					</view>
					<view class="goods-list">
						<view class="goods-item" v-for="(item, index) in orderData.purchaseDetailItemList" :key="index">
							<view class="goods-image">
								<image :src="item.goodsImage || '/static/images/default-goods.png'" mode="aspectFill"></image>
							</view>
							<view class="goods-info">
								<view class="name">{{ item.goodsName || '商品名称' }}</view>
								<view class="spec">数量: {{ item.quantity || 0 }}</view>
								<view class="price-amount">
									<text>单价: ¥{{ item.unitPrice && item.unitPrice.toFixed(2) || '0.00' }}</text>
									<text>金额: ¥{{ item.totalPrice && item.totalPrice.toFixed(2) || '0.00' }}</text>
								</view>
							</view>
						</view>
						<view v-if="!orderData.purchaseDetailItemList || orderData.purchaseDetailItemList.length === 0" class="empty-goods">
							<text>暂无商品信息</text>
						</view>
					</view>
				</view>

				<!-- 结算信息 -->
				<view class="settlement-section card">
					<view class="settlement-item">
						<text class="label">折后应付</text>
						<text class="value">¥{{ orderData.discountedAmount && orderData.discountedAmount.toFixed(2) || '0.00' }}</text>
					</view>
					<view class="settlement-item">
						<text class="label">折扣率</text>
						<text class="value">{{ calculateDiscountRate(orderData.totalAmount, orderData.discountedAmount) }}%</text>
					</view>
					<view class="settlement-item">
						<text class="label">本单实付</text>
						<text class="value">¥{{ orderData.actualPayment && orderData.actualPayment.toFixed(2) || '0.00' }}</text>
					</view>
					<view class="settlement-item">
						<text class="label">结算账户</text>
						<text class="value">{{ orderData.paymentMethod  || 'N/A' }}</text> <!-- 显示账户名称或ID -->
					</view>
				</view>

				<!-- 备注信息 -->
				<view class="remark-section card">
					<view class="section-header">备注</view>
					<view class="remark-content">{{ orderData.remark || '无' }}</view>
					<view class="order-code">单据编号: {{ orderData.orderCode || 'N/A' }}</view>
				</view>
				<view class="order-bottom"></view>
			</view>
		</scroll-view>

		<!-- 底部操作按钮 -->
		<view class="footer-actions">
			<button class="btn-delete" @click="deletePurchase">删除</button>
			<button class="btn-edit" @click="editPurchase">编辑</button>
		</view>

	</view>
</template>

<script>
import api from '@/utils/api.js';

export default {
	data() {
		return {
			purchaseId: null,
			orderData: {
				businessDate: '',
				supplierName: '',
				supplierId: null,
				purchaseDetailItemList: [],
				totalAmount: 0,
				discountedAmount: 0,
				actualPayment: 0,
				accountName: '', // 优先显示账户名称
				accountId: '',   // 其次显示账户ID
				remark: '',
				orderCode: '',
				// 可以添加更多从API获取的字段
			},
			isLoading: false,
			supplierInfo: null,
		};
	},
	onLoad(options) {
		if (options.id) {
			this.purchaseId = options.id;
			// this.loadPurchaseDetail();
		} else {
			uni.showToast({
				title: '无效的进货单ID',
				icon: 'none',
				duration: 2000
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 2000);
		}
	},
	onShow() {
		if (this.purchaseId) {
			this.loadPurchaseDetail();
		}
	},
	methods: {
		async loadPurchaseDetail() {
			if (!this.purchaseId) return;
			this.isLoading = true;
			uni.showLoading({ title: '加载中...' });

			try {
				// 确保 api.js 中有 getPurchaseDetail 函数
				if (!api.getPurchaseDetail) {
					throw new Error('API function getPurchaseDetail is not defined');
				}
				const res = await api.getPurchaseDetail(this.purchaseId);
				console.log('进货单详情:', res);
				const goodsList = await api.getGoodsListByReceiptCode(res.receiptCode);
				console.log('商品列表结果:', goodsList);

				// 根据后端实际返回的数据结构调整这里的字段赋值
				if (res && (res.data || res)) { // 假设数据在 res.data 或直接是 res
					const data = res.data || res;
					this.orderData = {
						...data,
						businessDate: data.businessDate ? data.businessDate.split(' ')[0] : 'N/A', // 格式化日期
						supplierName: data.supplierName || '未知供应商',
						supplierId: data.supplierId,
						purchaseDetailItemList: goodsList,
						totalAmount: parseFloat(data.totalAmount || 0),
						discountedAmount: parseFloat(data.discountedAmount || 0),
						actualPayment: parseFloat(data.actualPayment || 0),
						accountName: data.accountName || '', // 尝试获取账户名
						accountId: data.accountId || '未知账户',   // 获取账户ID
						remark: data.remark || '',
						orderCode: data.receiptCode || data.documentNumber || 'N/A', // 尝试不同字段
						// ... 其他字段
					};
					
					// 如果有供应商ID，获取供应商详情
					if (data.supplierId) {
						await this.loadSupplierInfo(data.supplierId);
					}
				} else {
					uni.showToast({ title: '获取详情失败', icon: 'none' });
				}
			} catch (err) {
				console.error('加载进货单详情失败:', err);
				uni.showToast({
					title: `加载失败: ${err.message || ''}`,
					icon: 'none'
				});
				// 可选择加载失败后返回上一页
				// setTimeout(() => uni.navigateBack(), 1500);
			} finally {
				this.isLoading = false;
				uni.hideLoading();
			}
		},

		calculateDiscountRate(total, discounted) {
			if (total && total > 0 && discounted !== undefined) {
				const rate = (discounted / total) * 100;
				return rate.toFixed(2); // 保留两位小数
			}
			return '100.00'; // 默认或无法计算时
		},

		editPurchase() {
			// 编辑页面的路径，并传递ID
			const editUrl = '/pages/purchase/edit?id=' + this.purchaseId; // 示例：复用开单页
			uni.navigateTo({
				url: editUrl
			});
		},

		deletePurchase() {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这条进货单记录吗？此操作不可恢复。',
				success: async (res) => {
					if (res.confirm) {
						uni.showLoading({ title: '删除中...' });
						try {
							// 确保 api.js 中有 deletePurchase 函数
							if (!api.deletePurchase) {
								throw new Error('API function deletePurchase is not defined');
							}
							await api.deletePurchase(this.purchaseId).then(res=>{
								uni.showToast({
									title: '删除成功',
									icon: 'success',
									duration: 1500
								});
								// 通知列表页刷新（如果需要）
								uni.$emit('refreshDetailList');
								setTimeout(() => {
									uni.navigateBack();
								}, 1500);
							}).catch(err=>{
								console.error('删除进货单失败:', err);
							});
						
						} catch (err) {
							console.error('删除进货单失败:', err);
							uni.showToast({
								title: `删除失败: ${err.message || ''}`,
								icon: 'none'
							});
						} finally {
							uni.hideLoading();
						}
					}
				}
			});
		},

		async loadSupplierInfo(supplierId) {
			console.log(`开始获取供应商(ID=${supplierId})详情`);
			if (!supplierId) {
				console.warn('无效的供应商ID，无法获取供应商详情');
				return;
			}
			
			try {
				// 确保API中有getSupplier函数
				if (!api.getSupplier && !api.getSupplierCategory) {
					console.error('API function getSupplier/getSupplierCategory is not defined');
					return;
				}
				
				// 使用合适的API函数获取供应商详情
				const res = await api.getSupplier(supplierId);
				console.log('供应商详情结果:', res);
				
				if (res && (res.data || res)) {
					const supplierData = res.data || res;
					// 保存供应商详情
					this.supplierInfo = supplierData;
					
					// 更新orderData中的供应商名称
					if (supplierData.supplierName) {
						this.orderData.supplierName = supplierData.supplierName;
						console.log(`已更新供应商名称为: ${supplierData.supplierName}`);
					}
				} else {
					console.warn('供应商详情返回数据为空');
				}
			} catch (err) {
				console.error('获取供应商详情失败:', err);
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.purchase-detail-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f5f7fa;
}

.scroll-view-content {
	flex: 1;
	overflow-y: auto;
	padding-bottom: 140rpx; /* 为底部按钮留出空间 */
}

.content-padding {
	padding: 20rpx;
}

.card {
	background-color: #ffffff;
	border-radius: 16rpx;
	margin-bottom: 20rpx;
	padding: 24rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

/* 基础信息 */
.info-section {
	.info-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		min-height: 80rpx;
		font-size: 28rpx;
		border-bottom: 1rpx solid #f0f0f0;

		&:last-child {
			border-bottom: none;
		}

		.label {
			color: #666;
			width: 150rpx; // 固定标签宽度
		}
		.value {
			color: #333;
			flex: 1;
			text-align: right;
		}
	}
}

/* 商品信息 */
.goods-section {
	.section-header {
		display: flex;
		justify-content: space-between;
		font-size: 26rpx;
		color: #666;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
		margin-bottom: 10rpx;
	}

	.goods-list {
		.goods-item {
			display: flex;
			padding: 20rpx 0;
			border-bottom: 1rpx dashed #eee; // 虚线分隔

			&:last-child {
				border-bottom: none;
			}

			.goods-image {
				width: 100rpx;
				height: 100rpx;
				margin-right: 20rpx;
				flex-shrink: 0;
				image {
					width: 100%;
					height: 100%;
					border-radius: 8rpx;
					background-color: #f0f0f0;
				}
			}

			.goods-info {
				flex: 1;
				font-size: 24rpx;
				color: #666;
				.name {
					font-size: 28rpx;
					color: #333;
					margin-bottom: 8rpx;
					font-weight: 500;
				}
				.spec {
					margin-bottom: 8rpx;
				}
				.price-amount {
					display: flex;
					justify-content: space-between;
					text {
						color: #888;
					}
				}
			}
		}
		.empty-goods {
			text-align: center;
			color: #999;
			font-size: 26rpx;
			padding: 40rpx 0;
		}
	}
}

/* 结算信息 */
.settlement-section {
	.settlement-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		min-height: 80rpx;
		font-size: 28rpx;
		border-bottom: 1rpx solid #f0f0f0;

		&:last-child {
			border-bottom: none;
		}

		.label {
			color: #666;
			width: 150rpx;
		}
		.value {
			color: #333;
			flex: 1;
			text-align: right;
			font-weight: 500;
			&.rate { // 折扣率特殊颜色
				color: #fa3534;
			}
		}
	}
}

/* 备注信息 */
.remark-section {
	.section-header {
		font-size: 26rpx;
		color: #666;
		margin-bottom: 15rpx;
	}
	.remark-content {
		font-size: 28rpx;
		color: #333;
		line-height: 1.6;
		min-height: 60rpx; // 保证即使没备注也有一定高度
		word-break: break-all; // 长单词换行
	}
	.order-code {
		margin-top: 20rpx;
		padding-top: 20rpx;
		border-top: 1rpx solid #f0f0f0;
		font-size: 24rpx;
		color: #999;
		text-align: right;
		padding-bottom: 40rpx;
	}
}


/* 底部操作按钮 */
.footer-actions {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 120rpx;
	background-color: #ffffff;
	display: flex;
	align-items: center;
	justify-content: space-around;
	padding: 15rpx 30rpx calc(15rpx + constant(safe-area-inset-bottom)); // 适配 iPhone X 等
	padding: 15rpx 30rpx calc(15rpx + env(safe-area-inset-bottom));
	box-shadow: 0 -4rpx 10rpx rgba(0, 0, 0, 0.05);

	button {
		flex: 1;
		height: 70rpx;
		line-height: 70rpx;
		border-radius: 35rpx;
		font-size: 28rpx;
		margin: 0 15rpx;
	}

	.btn-delete {
		border: 1rpx solid #fa3534;
		color: #fa3534;
		background-color: #fff;
	}

	.btn-edit {
		background-color: #39C9BB; // 主题色
		color: #fff;
		border: none;
	}
}
</style>
